/**
 * User: zsquirrel
 * Date: 2020/5/11
 * Time: 5:29 下午
 */
package com.cskaoyan.mall.dao;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.mall.model.User;
import com.cskaoyan.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> allUser() {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<User> users = null;
        try {
            users = runner.query("select * from user", new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    @Override
    public List<User> searchUser(String word) {
        String sql = "select * from user where 1 = 1 ";
        Object[] params = null;
        if(!StringUtils.isEmpty(word)){
            params = new Object[1];
            sql = sql + " and nickname like ?";
            params[0] = "%" + word + "%";
        }
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<User> users = null;
        try {
            users = runner.query(sql, new BeanListHandler<User>(User.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    @Override
    public void signup(User user) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update("insert into user values (null,?,?,?,?,?,?)",
                    user.getEmail(),
                    user.getNickname(),
                    user.getPwd(),
                    user.getRecipient(),
                    user.getAddress(),
                    user.getPhone());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
